﻿using DoNet.ApiHttpClient.Certificate;
using System.Security.Cryptography.X509Certificates;

namespace DoNet.ApiHttpClient.WechatMch
{
    /// <summary>
    /// HttpClient请求级证书注入实现方案，支持动态证书切换和普通请求混合模式
    /// </summary>
    public class WechatMchHttpHandler : DelegatingHandler
    {
        private readonly WechatMchManager _certManager;
        private readonly ICertSelector _certSelector;

        public WechatMchHttpHandler(WechatMchManager certManager, ICertSelector certSelector)
        {
            _certManager = certManager;
            _certSelector = certSelector;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var certId = _certSelector.SelectCertForRequest(request);
            if (!string.IsNullOrEmpty(certId))
            {
                var cert = _certManager.GetCertificate(certId);
                request.Options.Set(new HttpRequestOptionsKey<X509Certificate2>("Certificate"), cert);
            }

            return await base.SendAsync(request, cancellationToken);
        }
    }
}
